package com.api.sw.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.jsp.JspWriter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class SWUtil {
    public static boolean  getFloat(String str){
        boolean flag=false;
        float time=0.0f;
        try{
            time=Float.parseFloat(str);
            if(time>=0){
                flag=true;
            }
        }catch(Exception e){

        }
        return flag;
    }
    public static String postUrlDataResultByPost(String requestUrl, String param, JspWriter out1) throws Exception {
        Logger log = Logger.getLogger(JSONObject.class);
        String str = "";
        try{
            URL url = new URL(requestUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);// 需要输出
            connection.setDoInput(true);// 需要输入
            connection.setUseCaches(false);// 不允许缓存
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");// 设置请求方式
            connection.setRequestProperty("Accept", "application/json");// 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "multipart/form-data;charset=UTF-8"); // form表单
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(param.getBytes("UTF-8"));
            out.flush();
            out.close();
            InputStream input = null;
            out1.print(connection.getResponseCode());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                input = connection.getInputStream();
                StringBuilder inputLine = new StringBuilder();

                BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
                while ((str = reader.readLine()) != null) {
                    inputLine.append(str);
                }
                reader.close();

                str = inputLine.toString();
                if (str.startsWith("\"") && str.endsWith("\"")) {
                    str = str.substring(1, str.length() - 1);
                }

                return str;
            } else {
                input = connection.getErrorStream();
                StringBuilder inputLine = new StringBuilder();
                //String str = "";
                BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
                while ((str = reader.readLine()) != null) {
                    inputLine.append(str);
                }
                reader.close();

                str = inputLine.toString();
                //logger.debug("------ postUrlDataResultByPost Exception: " + str);
            }
        }catch(Exception e){
            out1.print(e.getMessage());
            str=e.getMessage();
        }
        return str;
    }

    /**
     * 把 \\u 开头的单字转成汉字，如 \\u6B65 ->　步
     * @param str
     * @return
     */
    public static String ustartToCn( String str) {
        StringBuilder sb = new StringBuilder().append("0x")
                .append(str.substring(2, 6));
        Integer codeInteger = Integer.decode(sb.toString());
        int code = codeInteger.intValue();
        char c = (char)code;
        return String.valueOf(c);
    }

    /**
     * 字符串是否以Unicode字符开头。约定Unicode字符以 \\u开头。
     * @param str 字符串
     * @return true表示以Unicode字符开头.
     */
    public static boolean isStartWithUnicode(final String str) {
        // 单个字符的正则表达式
        String singlePattern = "[0-9|a-f|A-F]";
        // 4个字符的正则表达式
        String pattern = singlePattern + singlePattern +
                singlePattern + singlePattern;
        if (null == str || str.length() == 0) {
            return false;
        }
        if (!str.startsWith("\\u")) {
            return false;
        }
        // \u6B65
        if (str.length() < 6) {
            return false;
        }
        String content = str.substring(2, 6);

        boolean isMatch = Pattern.matches(pattern, content);
        return isMatch;
    }

    /**
     * 字符串中，所有以 \\u 开头的UNICODE字符串，全部替换成汉字
     * @param str
     * @return
     */
    public static String unicodeToCn(final String str) {
        // 用于构建新的字符串
        StringBuilder sb = new StringBuilder();
        // 从左向右扫描字符串。tmpStr是还没有被扫描的剩余字符串。
        // 下面有两个判断分支：
        // 1. 如果剩余字符串是Unicode字符开头，就把Unicode转换成汉字，加到StringBuilder中。然后跳过这个Unicode字符。
        // 2.反之， 如果剩余字符串不是Unicode字符开头，把普通字符加入StringBuilder，向右跳过1.
        int length = str.length();
        for (int i = 0; i < length;) {
            String tmpStr = str.substring(i);
            if (isStartWithUnicode(tmpStr)) { // 分支1
                sb.append(ustartToCn(tmpStr));
                i += 6;
            } else { // 分支2
                sb.append(str.substring(i, i + 1));
                i++;
            }
        }
        return sb.toString();
    }
    //Map转  JSON
    public Map<String,Object> CovenyMap(JSONObject json){
        Map<String,Object> map=new HashMap<String,Object>();
        if(json!=null&&json.size()>0){
            Set<String> key=json.keySet();
            for(String str:key){
                map.put(str,json.get(str));
            }
        }
        return map;
    }
    public static String postUrlDataResult(String strArry) throws MalformedURLException, IOException {
        URL realurl = new URL(strArry);
        BufferedReader reader = new BufferedReader(new InputStreamReader(realurl.openStream()));
        StringBuilder inputLine = new StringBuilder();
        String str = "";
        while ((str = reader.readLine()) != null) {
            inputLine.append(str);
        }
        str = inputLine.toString();
        if (str.startsWith("\"") && str.endsWith("\"")) {
            str = str.substring(1, str.length() - 1);
        }
        if (str.contains("</")) {
            str = str.substring(str.indexOf(">") + 1, str.lastIndexOf("<"));
        }
        return str;
    }
}
